import React from 'react';
import _ from 'lodash';
import classNames from 'classnames';
import {toJS} from 'mobx';
import { WeaLocaleProvider } from 'ecCom';

const { getLabel } = WeaLocaleProvider;

export default class MobileRow extends React.Component {

  mobileRowRef = React.createRef();
  
  state = {
    refresh: true,
    rowValue: []
  };

  componentDidMount() {
    const { data: { defaultRowValue }, value } = this.props.parentProps;
    const {rowIndex} = this.props;
    let rowValue = [];

    if(rowIndex < 0) {
      rowValue = _.cloneDeep(toJS(defaultRowValue));
    }else{
      rowValue = _.cloneDeep(value[rowIndex])
    }

    this.setState({rowValue});
  }

  componentWillReceiveProps(nextProps){
      const { parentProps: { value }, rowIndex } = this.props;
      const nextRowIndex = nextProps.rowIndex;

      if(nextRowIndex != rowIndex){
        this.setState({rowValue:value[nextProps.rowIndex]});
      }
  }

  onRowCancel = () => {
    const { onChangeRow, rowIndex } = this.props;
    const { data: { coms }, value, onChange } = this.props.parentProps;
    const newValue = toJS(value);

    //取消后重置error
    coms.forEach(com => com && (com.error = ''))

    if( rowIndex == -1 ) {
      newValue.pop();
    } else {
      newValue[rowIndex] = this.state.rowValue;
    }

    onChange(newValue);
    onChangeRow(false);
  }

  //确认方法，
  onSure = () => {
    const { parentProps: { value }, onChangeRow, rowIndex } = this.props;
    //添加前进行校验
    const isValid = this.onValid();

    if(isValid){
      this.setState({rowValue:value[rowIndex]});
      onChangeRow(false);
    }   
  }

  scrollToError() {
    const container = this.mobileRowRef.current;
    const erroComDOM = container.querySelector('.wea-edc-has-error');

    if (erroComDOM) {
        container.scrollTop = erroComDOM.offsetTop;
    }
  }

  //校验
  onValid = () => {
    const { data: { coms }, value } = this.props.parentProps;

    let errorCom = coms.find((com, index) => {
      if(!com) return false;//当人员组件不显示时，人员组件不做校验

      const len = value.length - 1;
      const val = value[len][index];

      com.value = val;

      return !this.isComValid(com);
    });

    const refresh = this.state.refresh;

    this.setState({refresh:!refresh},() => {
      this.scrollToError();
    });
    return !errorCom;
  } 
  //判断是否有不满足规则的元素
  isComValid(com) {
    com.valid = true;
    com.error = '';

    com.rules.every(rule => {
      const { error, valid } = this.validate(rule, com);

      if (valid) return true;

      com.valid = false;
      com.error = error;
    });

    return com.valid;
  }

  validate(rule, field) {
    const valid = rule.validate(field);
    const error = !valid ? rule.error(field) : '';

    return { valid, error };
  }

  onContinue = () => {
    const { addRow } = this.props;
    const isValid = this.onValid();

    if(isValid){
      addRow(true);
      const refDom = this.mobileRowRef.current;

      refDom.scrollTo(0, 0);
    }
    
  }

  onComValueChange(val, rowIndex, colIndex) {
    const {data: { coms } } = this.props.parentProps;

    this.onValueChange(newValue => {
      newValue[rowIndex][colIndex] = val;
    });
    //给com赋值
    coms[colIndex].value = val;
    }

  onValueChange(handle) {
    const { value, onChange } = this.props.parentProps;
    const newValue = toJS(value);

    handle(newValue);
    onChange(newValue);
    
  }
  
  renderRowButtons(){
    return (
      <div className='mobile-row-btns'>
        <div className="mobile_cancel row-btn" onClick={this.onRowCancel}><span>{getLabel('31129', '取消')}</span></div>
        <div className="mobile_sure row-btn c-blue" onClick={this.onSure}><span>{getLabel('511767','确认')}</span></div>
        <div className="mobile_continueSave row-btn"onClick={this.onContinue}><span>{getLabel('511766','继续添加')}</span></div>
      </div>
    )
  }

  render(){
    const { isShow, rowIndex} = this.props;
    const { data: { coms, errors, defaultRowValue }, renderItem, value } = this.props.parentProps;
    const htmls = [];
    const vLength = value.length - 1 < 0 ? 0: value.length -1;
    const editIndex = rowIndex == -1 ? vLength : rowIndex;
    const clsNameStr = classNames('mobile-row', {
        'all-height': isShow
      });
    const maskClsName = classNames('mobile-mask', {
      'wea-hide': !isShow
    })
    
    //渲染所有的元素
    coms.forEach((com, colIndex) => {
      if(!com)return;
      const uuid = com.uuid;
      
      htmls.push(renderItem(com, {
      key: `${uuid}_${editIndex}_${colIndex}`,
      value: value[editIndex] ? value[editIndex][colIndex] : defaultRowValue[colIndex],
      error: !com.error ? '' : com.error,
      onChange: value => this.onComValueChange(value, editIndex, colIndex)
      }));
    });

    return (
      <React.Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@u6iumx`}>
        <div className={maskClsName} onClick={this.onRowCancel}></div>
        <div className={clsNameStr}>
          <div className='mobile-row-main' ref={this.mobileRowRef} >
            {htmls.map(item => (item))}
            </div>
            {this.renderRowButtons()}
          </div>
      </React.Fragment>
    )
  }
    
}